// utils/fileDownload.js
export default {
  /**
   * 下载 URL 到临时文件（_doc/）
   */
  download(url, fileName) {
		console.log(url);
    return new Promise((resolve, reject) => {
      uni.downloadFile({
        url,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve({ tempPath: res.tempFilePath, fileName });
          } else {
            reject("下载失败：" + res.statusCode);
          }
        },
        fail: reject
      });
    });
  },

  /**
   * 写入 Android 公共目录（Downloads）
   * 使用 MediaStore，支持 Android 10 ～ 16
   */
  saveToDownloads(tempPath, fileName, mimeType = "*/*") {
    if (plus.os.name !== "Android") {
      uni.showToast({ title: '仅支持 Android', icon: 'none' });
      return;
    }

    const main = plus.android.runtimeMainActivity();
    const File = plus.android.importClass("java.io.File");
    const FileInputStream = plus.android.importClass("java.io.FileInputStream");

    const MediaStore = plus.android.importClass("android.provider.MediaStore");
    const ContentValues = plus.android.importClass("android.content.ContentValues");
    const Environment = plus.android.importClass("android.os.Environment");

    const resolver = main.getContentResolver();

    const values = new ContentValues();
    values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
    values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
    values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);

    // Insert file into public Downloads folder
    const uri = resolver.insert(MediaStore.Downloads.getContentUri("external"), values);

    const fis = new FileInputStream(new File(tempPath));
    const os = resolver.openOutputStream(uri);

    let buffer = plus.android.newByteArray(8192);
    let len;

    while ((len = fis.read(buffer)) !== -1) {
      os.write(buffer, 0, len);
    }

    os.flush();
    os.close();
    fis.close();

    return uri;
  },

  /**
   * 识别 MIME 类型
   */
  getMimeType(fileName) {
    const ext = fileName.split(".").pop().toLowerCase();
    const map = {
      pdf: "application/pdf",
      doc: "application/msword",
      docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      xls: "application/vnd.ms-excel",
      xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      ppt: "application/vnd.ms-powerpoint",
      pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
      zip: "application/zip",
      rar: "application/x-rar-compressed",
      txt: "text/plain",
      jpg: "image/jpeg",
      jpeg: "image/jpeg",
      png: "image/png",
    };
    return map[ext] || "*/*";
  },

  /**
   * 下载 + 保存到公共目录（封装入口）
   */
  async downloadAndSave(url, fileName = null) {
    if (!fileName) {
      fileName = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
    }

    const mimeType = this.getMimeType(fileName);

    // 1 下载到 _doc/ 临时目录
    const { tempPath } = await this.download(url, fileName);

    // 2 写入系统 Downloads
    const uri = this.saveToDownloads(tempPath, fileName, mimeType);

    return {
      fileName,
      uri,
      mimeType,
      path: `/storage/emulated/0/Download/${fileName}`
    };
  }
};
